﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using Fiddler;
using System.Threading;
using FiddlerExUtils.Tools;
using System.Collections;

namespace FiddlerExScripts
{
    public partial class TreeViewControl : UserControl
    {
        /// <summary>
        /// 请求断点列表
        /// </summary>
        public static ArrayList bpuURI = new ArrayList();
        /// <summary>
        /// 响应断点列表
        /// </summary>
        public static ArrayList bpaURI = new ArrayList();
        private static readonly object objLock1 = new object();
        private static readonly object objLock2 = new object();
        /// <summary>
        /// Session队列
        /// </summary>
        private readonly Queue<Session> sessionQueue = new Queue<Session>();

        /// <summary>
        /// Focus Url list
        /// </summary>
        private static ArrayList focusHostList = new ArrayList();
        /// <summary>
        /// Ignore Url list
        /// </summary>
        private static ArrayList ignoreHostList = new ArrayList();
        private static string otherHosts = "Other Hosts";

        public TreeViewControl()
        {
            InitializeComponent();
            CommonFunction.DoubleBuffered(treeView1, true);
            treeView1.ImageList = imageList1;
            treeView1.ItemDrag += TreeView1_ItemDrag;
        }

        /// <summary>
        /// 启用异步线程处理
        /// </summary>
        public void SessionStart()
        {
            try
            {
                //异步处理
                new Thread(DGVWriteThread)
                {
                    IsBackground = true
                }.Start();
            }
            catch (Exception e)
            {
                FiddlerApplication.Log.LogString(e.StackTrace);
            }
        }

        /// <summary>
        /// Session入队
        /// </summary>
        /// <param name="oSession"></param>
        public void EnqueueSession(Session oSession)
        {
            try
            {
                lock (objLock1)
                {
                    sessionQueue.Enqueue(oSession);
                }
            }
            catch (Exception)
            {
                
            }
        }

        /// <summary>
        /// Session处理线程
        /// </summary>
        private void DGVWriteThread()
        {
            Session oSession;
            while (true)
            {
                lock (objLock2)
                {
                    oSession = null;
                    if (sessionQueue.Count > 0)
                    {
                        try
                        {
                            oSession = (Session)sessionQueue.Dequeue();
                        }
                        catch (Exception e)
                        {
                            FiddlerApplication.Log.LogString(e.StackTrace);
                        }
                    }
                    else
                    {
                        Thread.Sleep(500);
                        continue;
                    }
                }

                if (oSession != null)
                {
                    UpdateControl(oSession);
                    //Application.DoEvents();

                }
            }
        }
        /// <summary>
        /// 更新TreeView
        /// </summary>
        /// <param name="oSession"></param>
        public void UpdateControl(Session oSession)
        {
            if (oSession.RequestMethod != "CONNECT")
            {
                foreach (string path in ignoreHostList)
                {
                    if (oSession.fullUrl.Contains(path))
                    {
                        return;
                    }
                }
                
                Invoke(
                                new Action(
                                    delegate
                                    {
                                        TreeNode sessionIsInNode = null;
                                        //查找Session是否已添加
                                        foreach (TreeNode node in treeView1.Nodes)
                                        {
                                            sessionIsInNode = SessionIsInNode(oSession, node);
                                            if (sessionIsInNode != null)
                                                break;
                                        }
                                        if (sessionIsInNode != null)
                                        {
                                            UpdateNode(oSession, sessionIsInNode);
                                        }
                                        else
                                        {
                                            string pathAndQuery = oSession.PathAndQuery;
                                            string path = pathAndQuery;
                                            string query = "";
                                            if (pathAndQuery.Contains("?"))
                                            {
                                                path = pathAndQuery.Substring(0, pathAndQuery.IndexOf("?")); //查询路径
                                                query = pathAndQuery.Substring(pathAndQuery.IndexOf("?"), pathAndQuery.Length - pathAndQuery.IndexOf("?")); //查询参数
                                            }
                                            string[] paths = path.TrimEnd('/').Split('/'); //路径按/分组
                                            paths[paths.Length - 1] = paths[paths.Length - 1] + query; //最后一组加上查询参数

                                            string host = string.Format("{0}{1}", oSession.isHTTPS ? "https://" : "http://", oSession.host);
                                            string serviceName = "";

                                            if (focusHostList.Count != 0 && !treeView1.Nodes.ContainsKey(otherHosts))
                                            {
                                                treeView1.Nodes.Add(otherHosts, otherHosts);
                                            }

                                            TreeNode[] treeNodes;
                                            if ((focusHostList.Count == 0 && !treeView1.Nodes.ContainsKey(otherHosts)) || focusHostList.Contains(host))
                                            {
                                                treeNodes = treeView1.Nodes.Find(host, false);
                                            }
                                            else
                                            {
                                                treeNodes = treeView1.Nodes[otherHosts].Nodes.Find(host, false);
                                            }
                                            //Host已存在
                                            if (treeNodes.Length > 0)
                                            {
                                                TreeNode treeNode = treeNodes[0];
                                                TreeNode parentNode = treeNodes[0];

                                                if (oSession.PathAndQuery == "/")
                                                {
                                                    treeNode = treeNode.Nodes.Add("/", "/");
                                                    UpdateNode(oSession, treeNode);
                                                }
                                                else
                                                {
                                                    for (int i = 0; i < paths.Length; i++)
                                                    {
                                                        if (paths[i] != "")
                                                        {
                                                            treeNode = PathIsInNode(paths[i], parentNode);
                                                            if (treeNode == null || i == paths.Length - 1) //路径末尾+查询参数
                                                            {
                                                                treeNode = parentNode.Nodes.Add(paths[i], paths[i]);
                                                                if (i == paths.Length - 1)
                                                                {
                                                                    UpdateNode(oSession, treeNode);
                                                                }
                                                            }
                                                            if (treeNode != null && i != paths.Length - 1)
                                                            {
                                                                treeNode.ImageKey = "folder.png";
                                                                treeNode.SelectedImageKey = "folder.png";
                                                            }
                                                            parentNode = treeNode;
                                                        }
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                TreeNode treeNode;
                                                if ((focusHostList.Count == 0 && !treeView1.Nodes.ContainsKey(otherHosts)) || focusHostList.Contains(host))
                                                {
                                                    treeNode = treeView1.Nodes.Add(host, host);
                                                }
                                                else
                                                {
                                                    treeNode = treeView1.Nodes[otherHosts].Nodes.Add(host, host);
                                                }

                                                if (oSession.PathAndQuery == "/")
                                                {
                                                    treeNode = treeNode.Nodes.Add("/", "/");
                                                    UpdateNode(oSession, treeNode);
                                                }
                                                else
                                                {
                                                    for (int i = 0; i < paths.Length; i++)
                                                    {
                                                        if (paths[i] != "")
                                                        {
                                                            treeNode = treeNode.Nodes.Add(paths[i], paths[i]);
                                                            treeNode.ImageKey = "folder.png";
                                                            treeNode.SelectedImageKey = "folder.png";
                                                            if (i == paths.Length - 1)
                                                            {
                                                                UpdateNode(oSession, treeNode);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                    }));
            }
        }
        /// <summary>
        /// 查找Node的Key含path的节点
        /// </summary>
        /// <param name="path"></param>
        /// <param name="treeNode"></param>
        /// <returns></returns>
        private TreeNode PathIsInNode(string path, TreeNode treeNode)
        {
            TreeNode[] treeNodes = treeNode.Nodes.Find(path, true);
            if (treeNodes.Length > 0)
            {
                return treeNodes[0];
            }
            return null;
        }
        /// <summary>
        /// 查找Node的Tag含oSession的节点
        /// </summary>
        /// <param name="oSession"></param>
        /// <param name="treeNode"></param>
        /// <returns></returns>
        private TreeNode SessionIsInNode(Session oSession, TreeNode treeNode)
        {
            TreeNodeCollection treeNodes = treeNode.Nodes;
            foreach (TreeNode node in treeNodes)
            {
                Session oS = (Session)node.Tag;
                //if (oS != null)
                //    FiddlerApplication.Log.LogString("TAG ID:" + oS.id + ", Session ID:" + oSession.id);
                if (oS != null && oS == oSession){
                    return node;
                }
                TreeNode treeNode1 =  SessionIsInNode(oSession, node);
                if (treeNode1 != null)
                    return treeNode1;
            }

            return null ;
        }
        /// <summary>
        /// 更新Node节点图标展示
        /// </summary>
        /// <param name="oSession"></param>
        /// <param name="treeNode"></param>
        private void UpdateNode(Session oSession, TreeNode treeNode)
        {
            if (oSession.state == SessionStates.SendingRequest)
            {
                treeNode.ImageKey = "Up.png";
                treeNode.SelectedImageKey = "Up.png";
            }
            else if (oSession.state == SessionStates.ReadingResponse)
            {
                treeNode.ImageKey = "Download.png";
                treeNode.SelectedImageKey = "Download.png";
            }
            else if (oSession.state == SessionStates.HandTamperRequest)
            {
                treeNode.ImageKey = "RequestPaused.png";
                treeNode.SelectedImageKey = "RequestPaused.png";
                treeNode.NodeFont = new Font(treeView1.Font.FontFamily, treeView1.Font.Size, FontStyle.Bold);
            }
            else if (oSession.state == SessionStates.HandTamperResponse)
            {
                treeNode.ImageKey = "ResponsePaused.png";
                treeNode.SelectedImageKey = "ResponsePaused.png";
                treeNode.NodeFont = new Font(treeView1.Font.FontFamily, treeView1.Font.Size, FontStyle.Bold);
            }
            else if (oSession.responseCode == 200 && oSession.ResponseHeaders.ExistsAndContains("Content-Type", "json"))
            {
                treeNode.ImageKey = "JSON.png";
                treeNode.SelectedImageKey = "JSON.png";
            }
            else if (oSession.responseCode == 200 && oSession.ResponseHeaders.ExistsAndContains("Content-Type", "html"))
            {
                treeNode.ImageKey = "HTML5.png";
                treeNode.SelectedImageKey = "HTML5.png";
            }
            else if (oSession.responseCode == 200 && oSession.ResponseHeaders.ExistsAndContains("Content-Type", "xml"))
            {
                treeNode.ImageKey = "XML.png";
                treeNode.SelectedImageKey = "XML.png";
            }
            else if (oSession.responseCode == 200 && oSession.ResponseHeaders.ExistsAndContains("Content-Type", "javascript"))
            {
                treeNode.ImageKey = "JS.png";
                treeNode.SelectedImageKey = "JS.png";
            }
            else if (oSession.responseCode == 200 && oSession.ResponseHeaders.ExistsAndContains("Content-Type", "css"))
            {
                treeNode.ImageKey = "CSS3.png";
                treeNode.SelectedImageKey = "CSS3.png";
            }
            else if (oSession.responseCode == 200 && oSession.ResponseHeaders.ExistsAndContains("Content-Type", "image/"))
            {
                treeNode.ImageKey = "Image.png";
                treeNode.SelectedImageKey = "Image.png";
            }
            else if (oSession.responseCode == 304)
            {
                treeNode.ImageKey = "3xx.png";
                treeNode.SelectedImageKey = "3xx.png";
            }
            else if (oSession.responseCode.ToString().StartsWith("4") || oSession.responseCode.ToString().StartsWith("5"))
            {
                treeNode.ImageKey = "ServerError.png";
                treeNode.SelectedImageKey = "ServerError.png";
            }
            else if(oSession.RequestMethod == "POST")
            {
                treeNode.ImageKey = "RequestUsedPost.png";
                treeNode.SelectedImageKey = "RequestUsedPost.png";
            }
            else
            {
                treeNode.ImageKey = "GeneralSuccessResponse.png";
                treeNode.SelectedImageKey = "GeneralSuccessResponse.png";
            }
            
            if (oSession.state == SessionStates.Done)
            {
                treeNode.NodeFont = new Font(treeView1.Font.FontFamily, treeView1.Font.Size, FontStyle.Regular);
                if (focusHostList.Contains(FindRootNode(treeNode).Text))
                {
                    treeNode.ForeColor = Color.Orange;
                }
            }
            treeNode.Tag = oSession;
            //treeNode.BackColor = Color.Orange;
            //Thread.Sleep(200);
            //treeNode.BackColor = SystemColors.Window;
        }
        /// <summary>
        /// 查找节点的根节点
        /// </summary>
        /// <param name="treeNode"></param>
        /// <returns></returns>
        private TreeNode FindRootNode(TreeNode treeNode)
        {
            TreeNode pNode = treeNode.Parent;
            if (pNode != null && pNode.Text != otherHosts)
            {
                return FindRootNode(pNode);
            }
            else
            {
                return treeNode;
            }
        }
        /// <summary>
        /// 是否需要递归移除父节点
        /// </summary>
        /// <param name="treeNode"></param>
        private void RequiredClearParentNode(TreeNode treeNode)
        {
            TreeNode pNode = treeNode.Parent;
            if (pNode != null)
            {
                TreeNode ppNode = pNode.Parent;
                if (pNode.Nodes.Count > 1)
                {
                    treeNode.Remove();
                }
                else
                {
                    treeNode.Remove();
                    RequiredClearParentNode(pNode);
                } 
            }
            else
            {
                treeNode.Remove();
                return;
            }
        }
        /// <summary>
        /// 根据Session在session列表查找
        /// </summary>
        /// <param name="sessionId"></param>
        /// <returns></returns>
        private ListViewItem FindSession(Session session)
        {
            foreach (ListViewItem item in FiddlerApplication.UI.lvSessions.Items)
            {
                if ((Session)item.Tag == session)
                {
                    return item;
                }
            }
            return null;
        }

        private void TreeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if ((e.Node).Tag != null)
            {
                Session os = (Session)(e.Node).Tag;
                //移除原session的选中状态
                foreach (ListViewItem listViewItem in FiddlerApplication.UI.lvSessions.SelectedItems)
                {
                    listViewItem.Selected = false;
                    listViewItem.Focused = false;
                }
                //Fiddler原生session列表同步选择
                ListViewItem item = FindSession(os);
                if (item != null)
                {
                    FiddlerApplication.UI.lvSessions.TopItem = item;
                    item.Focused = true;
                    item.Selected = true;
                    FiddlerApplication.UI.actUpdateInspector(true, true);
                }
                else
                {
                    FiddlerApplication.UI.addSession(os);
                    
                }
            }
            
        }

        private void TreeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if ((e.Node).Tag != null)
            {
                TreeView1_NodeMouseClick(sender, e);
                FiddlerApplication.UI.ActivateRequestInspector("RequestView");
                FiddlerApplication.UI.ActivateResponseInspector("ResponseView");
            }
        }

        private void ContextMenuStrip1_Opening(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Point pt = this.PointToClient(Cursor.Position);
            TreeNode nodeAt = treeView1.GetNodeAt(pt);
            if (nodeAt != null)
            {
                treeView1.SelectedNode = nodeAt;
            }

            if (nodeAt != null && treeView1.SelectedNode.Text == otherHosts)
            {
                TSMI_NodeFocus.Enabled = false;
                TSMI_NodeFocus.Checked = false;
                TSMI_NodeIgnore.Enabled = false;
                TSMI_NodeIgnore.Checked = false;
                TSMI_NodeRequestBreakpoint.Enabled = false;
                TSMI_NodeRequestBreakpoint.Checked = false;
                TSMI_NodeResponseBreakpoint.Enabled = false;
                TSMI_NodeResponseBreakpoint.Checked = false;
            }
            else
            {
                TSMI_NodeFocus.Enabled = true;
                TSMI_NodeIgnore.Enabled = true;
                TSMI_NodeRequestBreakpoint.Enabled = true;
                TSMI_NodeResponseBreakpoint.Enabled = true;

                Session oSession = (Session)treeView1.SelectedNode.Tag;
                string path;
                if (oSession != null)
                {
                    path = oSession.fullUrl;
                }
                else
                {
                    path = treeView1.SelectedNode.FullPath;
                    if (path.Contains(otherHosts))
                        path = path.Replace(otherHosts + "/", "");
                }
                //Request Breakpoint
                foreach (string uri in bpuURI)
                {
                    if (uri.Contains(path))
                    {
                        TSMI_NodeRequestBreakpoint.Checked = true;
                        break;
                    }
                    else
                    {
                        TSMI_NodeRequestBreakpoint.Checked = false;
                    }
                }
                //Response Breakpoint
                foreach (string uri in bpaURI)
                {
                    if (uri.Contains(path))
                    {
                        TSMI_NodeResponseBreakpoint.Checked = true;
                        break;
                    }
                    else
                    {
                        TSMI_NodeResponseBreakpoint.Checked = false;
                    }
                }
                //Focus
                TreeNode rNode = FindRootNode(treeView1.SelectedNode);
                if (focusHostList.Contains(rNode.Text))
                {
                    TSMI_NodeFocus.Checked = true;
                }
                else
                {
                    TSMI_NodeFocus.Checked = false;
                }
                //Ignore
                string fullPath;
                if (treeView1.SelectedNode.Nodes.Count == 0)
                {
                    fullPath = treeView1.SelectedNode.Parent.FullPath + "/" + treeView1.SelectedNode.Name;
                }
                else
                {
                    fullPath = treeView1.SelectedNode.FullPath;
                }
                if (ignoreHostList.Contains(fullPath))
                {
                    TSMI_NodeIgnore.Checked = true;
                }
                else
                {
                    TSMI_NodeIgnore.Checked = false;
                }
            }
        }

        private void TSMI_NodeFocus_Click(object sender, EventArgs e)
        {
            if (TSMI_NodeFocus.Checked)
            {
                //移除根节点，再添加到treeview
                TreeNode rNode = FindRootNode(treeView1.SelectedNode);
                rNode.Remove();
                //添加other Hosts节点
                if (!treeView1.Nodes.ContainsKey(otherHosts))
                {
                    treeView1.Nodes.Add(otherHosts, otherHosts);
                }
                //添加到focus列表
                if (!focusHostList.Contains(rNode.Text))
                {
                    focusHostList.Add(rNode.Text);
                }
                //移动非Focus节点到Other Hosts节点下
                RemoveNode(treeView1.Nodes);

                treeView1.Nodes.Add(rNode);
                //移除Other Hosts节点，再添加到treeview
                TreeNode otNode = treeView1.Nodes[otherHosts];
                otNode.Remove();
                treeView1.Nodes.Add(otNode);
                //Other Hosts节点为空则删除
                if (treeView1.Nodes.ContainsKey(otherHosts) && treeView1.Nodes[otherHosts].Nodes.Count == 0)
                {
                    treeView1.Nodes[otherHosts].Remove();
                }
            }
            else //取消Focus
            {
                TreeNode rNode = FindRootNode(treeView1.SelectedNode);
                if (focusHostList.Contains(rNode.Text))
                {
                    focusHostList.Remove(rNode.Text);
                }
                TreeNode rootNode = FindRootNode(treeView1.SelectedNode);
                rootNode.Remove();
                if (treeView1.Nodes.ContainsKey(otherHosts) && treeView1.Nodes[otherHosts].Nodes.Count == 0)
                {
                    treeView1.Nodes[otherHosts].Remove();
                }

                if (treeView1.Nodes.ContainsKey(otherHosts))
                {
                    treeView1.Nodes[otherHosts].Nodes.Add(rootNode);
                }
                else
                {
                    treeView1.Nodes.Add(otherHosts, otherHosts);
                    treeView1.Nodes[otherHosts].Nodes.Add(rootNode);
                }
                ////treeView1只有otherhosts节点时，释放到treeview下展示
                //if (treeView1.Nodes.ContainsKey(otherHosts) && treeView1.Nodes.Count == 1)
                //{
                //    TreeNodeCollection treeNodeCollection = treeView1.Nodes[otherHosts].Nodes;
                //    foreach(TreeNode node in treeView1.Nodes[otherHosts].Nodes)
                //    {
                //        node.Remove();
                //    }
                //    foreach (TreeNode node in treeNodeCollection)
                //    {
                //        treeView1.Nodes.Add(node);
                //    }
                //}
            }

        }

        private void RemoveNode(TreeNodeCollection treeNodeCollection)
        {
            foreach (TreeNode node in treeNodeCollection)
            {
                if (node.Text != otherHosts && !focusHostList.Contains(node.Text))
                {
                    node.Remove();
                    treeView1.Nodes[otherHosts].Nodes.Add(node);
                    RemoveNode(treeNodeCollection);
                    return;
                }
            }
        }

        private void TSMI_NodeIgnore_Click(object sender, EventArgs e)
        {
            string fullPath;
            if (treeView1.SelectedNode.Nodes.Count == 0)
            {
                fullPath = treeView1.SelectedNode.Parent.FullPath + "/" + treeView1.SelectedNode.Name;
            }
            else
            {
                fullPath = treeView1.SelectedNode.FullPath;
            }

            if (TSMI_NodeIgnore.Checked)
            {
                //添加到ignore列表
                if (!ignoreHostList.Contains(fullPath))
                {
                    ignoreHostList.Add(fullPath);
                }
            }
            else //取消Ignore
            {
                if (ignoreHostList.Contains(fullPath))
                {
                    ignoreHostList.Remove(fullPath);
                }
            }
        }

        private void TSMI_NodeClear_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                RequiredClearParentNode(treeView1.SelectedNode);
            }
        }

        private void TSMI_NodeClearOthers_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                //TreeNode rNode = FindRootNode(treeView1.SelectedNode);
                //for (int i=0; i < treeView1.Nodes.Count; )
                //{
                //    if (treeView1.Nodes[i] != null && treeView1.Nodes[i] != rNode)
                //    {
                //        treeView1.Nodes[i].Remove();
                //        i = 0;
                //    }
                //    else
                //    {
                //        i = i + 1;
                //    }
                //}
                TreeNode pNode = treeView1.SelectedNode.Parent;
                TreeNodeCollection treeNodeCollection;
                if (pNode == null)
                {
                    treeNodeCollection = treeView1.Nodes;
                }
                else
                {
                    treeNodeCollection = pNode.Nodes;
                }
                    
                for (int i = 0; i < treeNodeCollection.Count;)
                {
                    if (treeNodeCollection[i] != null && treeNodeCollection[i] != treeView1.SelectedNode)
                    {
                        treeNodeCollection[i].Remove();
                        i = 0;
                    }
                    else
                    {
                        i = i + 1;
                    }
                }
            }
        }

        private void TSMI_NodeRequestBreakpoint_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                Session oSession = (Session)treeView1.SelectedNode.Tag;
                string path;
                if (oSession != null)
                {
                    string serviceName = oSession.fullUrl;
                    if (serviceName == "")
                    {
                        path = oSession.fullUrl;
                    }
                    else
                    {
                        path = serviceName;
                    }
                }
                else
                {
                    path = treeView1.SelectedNode.FullPath;
                    if (path.Contains(otherHosts))
                        path = path.Replace(otherHosts + "/", "");
                }

                if (TSMI_NodeRequestBreakpoint.Checked == true)
                {
                    if (!bpuURI.Contains(path))
                    {
                        bpuURI.Add(path); 
                    }
                }
                else
                {
                    if (bpuURI.Contains(path))
                    {
                        bpuURI.Remove(path);
                    }
                }
            }
        }

        private void TSMI_NodeResponseBreakpoint_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                string path = "";
                Session oSession = (Session)treeView1.SelectedNode.Tag;
                if (oSession != null)
                {
                    string serviceName = oSession.fullUrl;
                    if (serviceName == "")
                    {
                        path = oSession.fullUrl;
                    }
                    else
                    {
                        path = serviceName;
                    }
                }
                else
                {
                    path = treeView1.SelectedNode.FullPath;
                    if (path.Contains(otherHosts))
                        path = path.Replace(otherHosts + "/", "");
                }

                if (TSMI_NodeResponseBreakpoint.Checked == true)
                {
                    if (!bpaURI.Contains(path))
                    {
                        bpaURI.Add(path);
                    }
                }
                else
                {
                    if (bpaURI.Contains(path))
                    {
                        bpaURI.Remove(path);
                    }
                }
            }
        }

        private void TSMI_NodeExpandAll_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                treeView1.SelectedNode.ExpandAll();
            }
        }

        private void TSMI_NodeCollapse_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                treeView1.SelectedNode.Collapse(true);
            }
        }

        private void TreeView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers == Keys.Control && e.KeyCode == Keys.X)
            {
                TSMI_NodeClear_Click(null, null);
            }
        }

        //开始拖动操作事件 
        private void TreeView1_ItemDrag(object sender, ItemDragEventArgs e)
        {
            TreeNode tn = e.Item as TreeNode;
            if ((e.Button == MouseButtons.Left) && (tn != null) && (tn.Nodes.Count == 0)) //非末节点不允许拖放操作。 
            {
                Session dragSession = (Session)tn.Tag;
                List<Session> sessionList = new List<Session>();
                Session session = new Session(dragSession);
                string decryptResponse = session.GetRequestBodyAsString();
                session.utilSetRequestBody(decryptResponse);
                sessionList.Add(session);
                Session[] os = sessionList.ToArray();
                this.treeView1.DoDragDrop(os, DragDropEffects.Copy);
            }
        }

        private void TreeView1_AfterExpand(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Level == 1)
            {
                e.Node.ExpandAll();
            }
        }
    }
}
